<template>
  <div class="price-comparison-list-container">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" class="search-form">
      <!-- 第一行：5个位置均分（4个搜索项+1个搜索按钮） -->
      <div class="search-row">
        <el-form-item label="项目名称" class="search-item">
          <el-input
            v-model="searchForm.project"
            placeholder="项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="资产编号" class="search-item">
          <el-input
            v-model="searchForm.assetCode"
            placeholder="资产编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="资产地址" class="search-item">
          <el-input
            v-model="searchForm.address"
            placeholder="资产地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="推送状态" class="search-item">
          <el-select
            v-model="searchForm.pushStatus"
            placeholder="推送状态"
            clearable
          >
            <el-option
              v-for="option in pushStatusOptions"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-button-item">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </div>

      <!-- 第二行：5个位置，1个搜索项+4个按钮位置 -->
      <div class="search-row">
        <el-form-item
          label="预警等级"
          class="search-item-second"
          v-if="props.warningType === '合同合规'"
        >
          <el-select
            v-model="searchForm.countDocumentWarningLevel"
            placeholder="预警等级"
            clearable
          >
            <el-option
              v-for="option in priceWarningLevelOptions"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="预警等级"
          class="search-item-second"
          v-if="props.warningType === '价格比对'"
        >
          <el-select
            v-model="searchForm.priceWarningLevel"
            placeholder="预警等级"
            clearable
          >
            <el-option
              v-for="option in priceWarningLevelOptions"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            />
          </el-select>
        </el-form-item>

        <div class="action-buttons">
          <el-button type="primary" @click="handleBatchRemoveWarning">
            批量解除预警
          </el-button>
          <el-button type="primary" @click="handleBatchPush"
            >批量推送</el-button
          >
          <el-button :loading="exportLoading" @click="handleOut">
            {{ exportLoading ? "导出中..." : "导出" }}
          </el-button>
        </div>
      </div>
    </el-form>

    <el-table
      :data="tableData"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
      :scroll="{ x: '90%' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column
        prop="project"
        label="项目名称"
        show-overflow-tooltip
        fixed="left"
        width="150"
      />
      <el-table-column
        prop="assetCode"
        label="资产编号"
        width="230"
        show-overflow-tooltip
      />
      <el-table-column
        prop="address"
        label="资产地址"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column label="预警分析" show-overflow-tooltip width="180">
        <template #default="{ row }">
          <div
            class="warning-status"
            style="display: flex; flex-wrap: wrap; gap: 8px"
          >
            <template v-if="row.warningType">
              <el-tag
                v-for="(text, idx) in row.warningType.split(';')"
                :key="idx"
                size="small"
                effect="light"
                :style="getWarningTagStyleByText(text)"
                @click.stop="handleWarningClickByText(text, row)"
              >
                {{ getWarningTextByText(text) }}
              </el-tag>
            </template>
            <span v-else>--</span>
          </div>
        </template>
      </el-table-column>
      <!-- 预警结果 -->
      <el-table-column
        prop="warningResult"
        label="预警结果"
        show-overflow-tooltip
        width="200"
      />
      <!-- 轻微、中等、严重 -->
      <el-table-column
        prop="countDocumentWarningLevel"
        label="预警等级"
        v-if="props.warningType === '合同合规'"
      >
        <template #default="{ row }">
          <el-tag
            :type="getLevelTagType(row.countDocumentWarningLevel)"
            disable-transitions
          >
            {{ row.countDocumentWarningLevel || "--" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="priceWarningLevel"
        label="预警等级"
        v-if="props.warningType === '价格比对'"
      >
        <template #default="{ row }">
          <el-tag
            :type="getLevelTagType(row.priceWarningLevel)"
            disable-transitions
          >
            {{ row.priceWarningLevel || "--" }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 推送成功 未推送 推送失败 -->
      <el-table-column prop="pushStatus" label="推送状态" width="150" />
      <el-table-column
        prop="originalUnit"
        label="资产权利人"
        show-overflow-tooltip
        width="200"
      />

      <el-table-column
        prop="companyName"
        label="管理单位"
        show-overflow-tooltip
        width="200"
      />

      <el-table-column
        prop="managerName"
        label="资产经办人"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column prop="count" label="资产数量" width="100">
        <template #default="{ row }">
          {{ row.count }}{{ getAssetUnit(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="资产类型" width="100" />
      <el-table-column prop="rentStatus" label="租赁状态" width="100" />
      <el-table-column label="资产文件" show-overflow-tooltip width="150">
        <template #default="{ row }">
          <div class="file-links">
            <template
              v-if="
                row.tenderDocUrl || row.contractDocUrl || row.evaluationDocUrl
              "
            >
              <template v-if="row.tenderDocUrl">
                <el-link
                  type="primary"
                  :underline="false"
                  class="file-link"
                  :href="row.tenderDocUrl"
                  target="_blank"
                >
                  招标
                </el-link>
              </template>
              <template v-if="getUrlList(row.contractDocUrl).length">
                <template
                  v-for="(url, idx) in getUrlList(row.contractDocUrl)"
                  :key="url"
                >
                  <el-link
                    type="primary"
                    :underline="false"
                    class="file-link"
                    :href="url"
                    target="_blank"
                  >
                    合同{{
                      getUrlList(row.contractDocUrl).length > 1 ? idx + 1 : ""
                    }}
                  </el-link>
                  <span
                    v-if="idx !== getUrlList(row.contractDocUrl).length - 1"
                    class="file-separator"
                  >
                    |
                  </span>
                </template>
              </template>
              <template v-if="row.evaluationDocUrl">
                <span
                  v-if="row.tenderDocUrl || row.contractDocUrl"
                  class="file-separator"
                  >|</span
                >
                <el-link
                  type="primary"
                  :underline="false"
                  class="file-link"
                  :href="row.evaluationDocUrl"
                  target="_blank"
                >
                  评估
                </el-link>
              </template>
            </template>
            <span v-else>--</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-link
            type="primary"
            :underline="false"
            style="padding: 0; margin-right: 24px"
            @click="handleRemoveWarning(row, props.warningType)"
          >
            解除预警
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            style="padding: 0"
            @click="handlePush(row)"
          >
            推送
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <span class="total-count">总共 {{ total }} 个项目</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 资产抽屉 -->
    <asset-drawer
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
    />

    <el-dialog v-model="pushDialogVisible" title="预警推送" width="500px">
      <div style="margin-bottom: 16px">
        <div style="font-weight: bold; margin-bottom: 8px">推送资产</div>
        <div>
          <el-tag
            v-for="item in pushAssetList"
            :key="item.id"
            style="margin: 0 8px 8px 0"
            type="info"
            disable-transitions
          >
            {{ item.project }}-{{ item.assetCode }}
          </el-tag>
        </div>
      </div>
      <div>
        <div style="font-weight: bold; margin-bottom: 8px">推送备注</div>
        <el-input
          v-model="pushRemark"
          type="textarea"
          :rows="5"
          placeholder="请输入推送原因"
        />
      </div>
      <template #footer>
        <el-button type="primary" @click="confirmPush" :loading="pushLoading"
          >推送</el-button
        >
        <el-button @click="pushDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { getPriceComparisonList, removeWarning, pushWarning } from "./services";
import {
  getRentPriceComparison,
  getDocumentReviewInfoByAssetCode,
} from "@/views/assetList/services";
import AssetDrawer from "@/views/assetList/components/AssetDrawer.vue";
import request from "@/utils/request";
import dayjs from "dayjs";

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const multipleSelection = ref([]);
const pushStatusOptions = ref([
  { label: "推送成功", value: "推送成功" },
  { label: "未推送", value: "未推送" },
  { label: "推送失败", value: "推送失败" },
]);

const priceWarningLevelOptions = ref([
  { label: "轻微", value: "轻微" },
  { label: "中等", value: "中等" },
  { label: "严重", value: "严重" },
]);

const props = defineProps({
  warningType: {
    type: String,
    default: "价格比对",
    required: true,
  },
});

const drawerType = ref("");
const drawerVisible = ref(false);
const currentAssetData = ref(null);

const searchForm = ref({
  project: "",
  address: "",
  countMin: null,
  countMax: null,
  assetCode: "",
  pushStatus: "",
  countDocumentWarningLevel: "",
  priceWarningLevel: "",
});

const fetchTableData = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    };
    const res = await getPriceComparisonList(params, props.warningType);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

onMounted(fetchTableData);

const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

const getUrlList = (url) => {
  if (!url) return [];
  if (typeof url === "string" && url.startsWith("[") && url.includes("http")) {
    // 提取所有 http(s) 链接
    return url.match(/https?:\/\/[^\],\s]+/g) || [];
  }
  if (typeof url === "string" && url.startsWith("http")) {
    return [url];
  }
  return [];
};

const warningTextMap = {
  空置: "vacancy",
  合同合规: "contract",
  价格比对: "price",
  价格比对: "price",
  无合同: "noContract",
};
const getWarningTextByText = (text) => {
  const map = {
    price: "价格比对",
    contract: "合同合规",
    vacancy: "空置监测",
    noContract: "无合同",
  };
  const key = warningTextMap[text] || text;
  return map[key] || text;
};
const getWarningTagStyleByText = (text) => {
  const styleMap = {
    price: {
      color: "#409EFF",
      background: "#E6F0FE",
      borderColor: "#409EFF",
      cursor: "pointer",
    },
    contract: {
      color: "#22C55E",
      background: "#E6F9F0",
      borderColor: "#22C55E",
      cursor: "pointer",
    },
    vacancy: {
      color: "#F59E42",
      background: "#FFF7E6",
      borderColor: "#F59E42",
      cursor: "pointer",
    },
    noContract: {
      color: "#F87171",
      background: "#FEECEC",
      borderColor: "#F87171",
      cursor: "not-allowed",
    },
  };
  const key = warningTextMap[text] || text;
  return styleMap[key] || {};
};

// 解除预警
const handleRemoveWarning = (row) => {
  ElMessageBox.confirm("确定要解除该资产的预警吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // TODO: 调用解除预警接口
      await removeWarning(row.id);
      ElMessage.success("解除预警成功");
    })
    .catch(() => {
      // 用户取消
    });
};

// 批量解除预警
function handleBatchRemoveWarning() {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请先选择要解除预警的资产");
    return;
  }
  const ids = multipleSelection.value.map((item) => item.id);
  const idsStr = ids.join(",");
  if (!idsStr) {
    ElMessage.warning("选中的资产ID为空");
    return;
  }
  ElMessageBox.confirm(`确定要批量解除选中资产的预警吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log("批量解除预警ID字符串:", idsStr);
      await removeWarning(idsStr);
      ElMessage.success("批量解除预警成功");
      fetchTableData();
    })
    .catch(() => {
      // 用户取消
    });
}

const getAssetUnit = (type) => {
  if (!type) return "㎡";
  const typeMap = {
    房屋资产: "㎡",
    土地资产: "㎡",
    车位资产: "个",
    其他资产: "个",
  };
  return typeMap[type] || "㎡";
};

function handleSelectionChange(val) {
  multipleSelection.value = val;
}

const handleWarningClickByText = (text, row) => {
  const key = warningTextMap[text] || text;
  if (key === "noContract") return;
  openDrawer(key, row);
};

// 打开抽屉
const openDrawer = async (type, row) => {
  console.log("Opening drawer:", type, row);
  drawerType.value = type;

  // 根据不同类型准备不同的数据
  if (type === "price") {
    try {
      currentAssetData.value = await getRentPriceComparison(row.id);
    } catch (error) {
      console.error("Failed to fetch price comparison data:", error);
      // Handle error appropriately
    }
  } else if (type === "contract") {
    try {
      const contractData = await getDocumentReviewInfoByAssetCode(
        row.assetCode
      );

      currentAssetData.value = {
        contractData: contractData.data.results,
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
      };
    } catch (error) {
      currentAssetData.value = {
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
        data: {},
      };
      // 可选：提示用户接口异常
    }
  } else if (type === "vacancy") {
  }

  currentAssetData.value = {
    ...currentAssetData.value,
    baseInfo: {
      project: row.project,
      assetCode: row.assetCode,
      address: row.address,
      count: row.count,
    },
  };

  drawerVisible.value = true;
  console.log(" currentAssetData.value======", currentAssetData.value);
};

const getLevelTagType = (level) => {
  if (level === "轻微") return "primary";
  if (level === "中等") return "warning";
  if (level === "严重") return "danger";
  return "";
};

const pushDialogVisible = ref(false);
const pushRemark = ref("");
const pushAssetList = ref([]);
const pushIds = ref([]);
const pushLoading = ref(false);

const handlePush = (row) => {
  pushAssetList.value = [row];
  pushIds.value = [row.id];
  pushRemark.value = "";
  pushDialogVisible.value = true;
};
const handleBatchPush = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请先选择要推送的资产");
    return;
  }
  pushAssetList.value = multipleSelection.value;
  pushIds.value = multipleSelection.value.map((item) => item.id);
  pushRemark.value = "";
  pushDialogVisible.value = true;
};
const confirmPush = async () => {
  if (!pushRemark.value.trim()) {
    ElMessage.warning("请填写推送备注");
    return;
  }
  pushLoading.value = true;
  try {
    await pushWarning({
      ids: pushIds.value.join(","),
      remark: pushRemark.value,
    });
    ElMessage.success("推送成功");
    pushDialogVisible.value = false;
    fetchTableData();
  } catch (e) {
    ElMessage.error("推送失败");
  } finally {
    pushLoading.value = false;
  }
};

const exportLoading = ref(false);

const handleOut = async () => {
  try {
    exportLoading.value = true;
    // 拼接searchForm有值的字段到url上
    const urlParamsArr = [];
    Object.keys(searchForm.value).forEach((key) => {
      const value = searchForm.value[key];
      if (
        value !== undefined &&
        value !== null &&
        value !== "" &&
        !(Array.isArray(value) && value.length === 0)
      ) {
        urlParamsArr.push(
          `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        );
      }
    });
    urlParamsArr.push(`warningType=${encodeURIComponent(props.warningType)}`);
    const exportUrl = `/demo/assetInfo/export?${urlParamsArr.join("&")}`;

    // 调用原有的导出接口
    const res = await request({
      url: exportUrl,
      method: "post",
      responseType: "blob",
    });

    // 判断是否为后端错误信息
    if (res.type && res.type.indexOf("application/json") !== -1) {
      const reader = new FileReader();
      reader.onload = function () {
        try {
          const result = JSON.parse(reader.result);
          ElMessage.error(result.msg || "导出失败");
        } catch {
          ElMessage.error("导出失败");
        }
      };
      reader.readAsText(res);
      exportLoading.value = false;
      return;
    }

    // 创建blob对象
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });

    // 创建下载链接
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);

    // 设置文件名，使用当前日期
    const date = new Date();
    const fileName = `工单数据_${date.getFullYear()}${String(
      date.getMonth() + 1
    ).padStart(2, "0")}${String(date.getDate()).padStart(2, "0")}.xlsx`;
    link.download = fileName;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
.price-comparison-list-container {
  padding: 20px;
  background: #fff;
}
.search-form {
  width: 100%;
}

.search-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.search-item,
.search-item-second,
.search-button-item {
  flex: 1 1 0;
  min-width: 0;
  // margin-right: 24px;
  margin-bottom: 0;
  max-width: none;

  :deep(.el-form-item__content) {
    width: 100%;
  }
  :deep(.el-input),
  :deep(.el-select) {
    width: 100%;
  }
  :deep(.el-input__wrapper),
  :deep(.el-select .el-input__wrapper) {
    width: 100%;
  }
}
.search-item:last-child,
.search-button-item {
  margin-right: 0;
}

:deep(.el-form-item__label) {
  width: 70px;
  min-width: 70px;
  text-align: right;
  padding-right: 8px;
}

.search-button-item {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  :deep(.el-form-item__content) {
    display: flex;
    // justify-content: flex-end;
    margin-left: 24px;
  }
}
.action-buttons {
  display: flex;
  gap: 8px;
  flex: 4;
  justify-content: flex-end;
}
.file-links {
  display: flex;
  gap: 8px;
  align-items: center;
}
.file-link {
  font-size: 13px;
  cursor: pointer;
}
.file-link:hover {
  opacity: 0.85;
}
.file-separator {
  color: #dcdfe6;
  margin: 0 4px;
}
.warning-status {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.total-count {
  color: #606266;
  font-size: 13px;
}
</style>
